<?php

namespace app\service;

use app\model\Auth;
use app\model\Admin;
use app\model\AdminRole;
use app\traits\Singleton;

class AdminService
{
    use Singleton;

    public function getAdminList($username, $page = 1, $pageSize = 10)
    {
        $fields = [
            "id",
            "username",
            "phone",
            "email",
            "avatar",
            "type",
            "create_time",
            "update_time"
        ];
        $model = Admin::field($fields)
            ->order('id', 'desc');

        if ($username) {
            $model->where("username", "like", "%{$username}%");
        }

        $paginator = $model
            ->page($page)
            ->paginate($pageSize);

        $data = array_map(function ($item) {
            return $item;
        }, $paginator->getCollection()->toArray());

        return [
            "list" => $data,
            "total" => $paginator->total()
        ];
    }
    public function createAdmin($username, $phone, $email, $type, $avatar, $pass, $salt)
    {
        return Admin::create([
            "username" => $username,
            "phone" => $phone,
            "email" => $email,
            "type" => $type,
            "avatar" => $avatar,
            "password" => $pass,
            "salt" => $salt
        ]);
    }

    public function updateAdmin($id, $username, $password, $phone, $email, $type)
    {
        return Admin::where("id", $id)->save([
            "username" => $username,
            "password" => $password,
            "phone" => $phone,
            "email" => $email,
            "type" => $type
        ]);
    }

    public function deleteAdmin($id)
    {
        return Admin::where("id", $id)->delete();
    }

    public function getUserInfoByUsername($username)
    {
        $data = Admin::where("username", $username)->find();
        return $data;
    }

    public function getUserMenus($user)
    {
        $userId = $user->id;
        $roleId = AdminRole::where("admin_id", $userId)->value("role_id");
        $menuIds = $roleId ? Auth::where("role_id", $roleId)->column("menu_id") : [];
        return [
            "username" => $user->username,
            "role_id" => $roleId,
            "menu_ids" => $menuIds
        ];
    }
}